package cc.smarnet.caihou;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import cc.smarnet.caihou.phone.MainPageActivity;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;

public class LoginActivity extends AppCompatActivity {
    private ImageView yangzhengma;
    private TextView loginAccount;
    private TextView loginPassword;
    private TextView yanzhengmaValue;
    private Button loginButton;
    private CheckBox checkBox;
    private ProgressBar progressBar;
    public boolean ifChecked = true;// 是否选中复选框，在界面中设置默认是选中的
    private long mExitTime;       //实现“再按一次退出”的记录时间变量

    long timeInMillis = 129282828;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        getSupportActionBar().hide();//隐藏标题栏
        initViews();

        getYanZhengMa();
        // 点击登录按钮监听
        yangzhengma.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getYanZhengMa();
            }
        });
        // 从SharedPreferences查看是否保存有ifChecked信息
        SharedPreferences spUser = getSharedPreferences("userInfo", MODE_PRIVATE);
        if (spUser.contains("checked")) {
            ifChecked = spUser.getBoolean("checked", true);
            checkBox.setChecked(ifChecked);
        }
        // 从SharedPreferences查看是否保存有用户信息,如果有用户信息则将从SharedPreferences中取出账号和密码塞到对应的文本框中
        SharedPreferences spAccount = getSharedPreferences("accountInfo", MODE_PRIVATE);
        if (spAccount.contains("account") && spAccount.contains("password")) {
            String account = spAccount.getString("account", null);
            String password = spAccount.getString("password", null);
            loginAccount.setText(account);
            loginPassword.setText(password);
            /*Intent intent = new Intent(LoginActivity.this, MainPageActivity.class);
            startActivity(intent);*/

        }
        // 记住登录状态复选框的监听
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ifChecked = isChecked;
            }
        });


        // 点击登录按钮监听
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressBar.setVisibility(View.VISIBLE);// 设置加载效果可见
                String account = loginAccount.getText().toString();
                String password = loginPassword.getText().toString();
                String yanzhengmaV = yanzhengmaValue.getText().toString();
                if (account.equals("")) {
                    progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                    Toast.makeText(LoginActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
                } else if (password.equals("")) {
                    progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                    Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                } else  if (yanzhengmaV.equals("")) {
                    progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                    Toast.makeText(LoginActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                } else {
                    loginButton.setEnabled(false);// 先设置登录按钮不可用
                    final Map<String, String> map = new HashMap<String, String>();
                    map.put("username", account);
                    map.put("password", password);
                    map.put("checkKey", String.valueOf( timeInMillis));
                    map.put("captcha", yanzhengmaV);


                    // 将map转为json字符串
                    String requestJsonString = JSON.toJSONString(map);

                    String url = IPConfig.baseUrl + "/sys/mLogin2";
                    // 使用OkHttpUtils发起http请求并得到返回结果
                    OkHttpUtils
                            .postString()
                            .url(url)
                            .content(requestJsonString)
                            .mediaType(MediaType.parse("application/json; charset=utf-8"))
                            .build()
                            .connTimeOut(100000)
                            .writeTimeOut(100000)
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                                    AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
                                    alertDialog.setMessage("访问服务器失败，请检查网络后再试，或联系系统管理员!");
                                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    });
                                    alertDialog.show();
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                                    boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                                    if (success) {
                                        String result = JSON.parseObject(response).getString("result");
                                        String userInfo = JSON.parseObject(result).getString("userInfo");
                                        String token = JSON.parseObject(result).getString("token");
                                        // 将复选框是否选中的状态、用户信息、token保存至SharedPreferences
                                        SharedPreferences spUser = getSharedPreferences("userInfo", MODE_PRIVATE);
                                        SharedPreferences.Editor editorUser = spUser.edit();
                                        editorUser.putBoolean("checked", ifChecked);
                                        editorUser.putString("userInfo", userInfo);
                                        editorUser.putString("token", token);
                                        /*
                                         * 这里用ccount1和password1是为了不和下面记住登录状态的account和password冲突，
                                         * 这这里用ccount1和password1是为了在有些登录进去后的页面中使用
                                         * */
                                        editorUser.putString("account1", account);
                                        editorUser.putString("password1", password);
                                        editorUser.commit();

                                        SharedPreferences spAccount = getSharedPreferences("accountInfo", MODE_PRIVATE);
                                        SharedPreferences.Editor editorAccount = spAccount.edit();
                                        // 如果选择了记住登录状态，则将用户信息保存至SharedPreferences
                                        if (ifChecked) {
                                            // 将账号信息保存至SharedPreferences
                                            editorAccount.putString("account", account);
                                            editorAccount.putString("password", password);
                                            editorAccount.commit();
                                        } else {
                                            if (spUser.contains("account")) {
                                                editorAccount.remove("account");
                                                editorAccount.remove("password");
                                                editorAccount.commit();
                                            }
                                        }
                                        Intent intent = new Intent(LoginActivity.this, MainPageActivity.class);
                                        //Intent intent = new Intent(LoginActivity.this, TestActivity.class);
                                        startActivity(intent);
                                    } else {
                                        AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
                                        alertDialog.setMessage(JSON.parseObject(response).getString("message"));
                                        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                // 清空账号和密码信息并使账号框获取焦点
//                                                loginPassword.setText("");
//                                                loginAccount.requestFocus();
                                            }
                                        });
                                        alertDialog.show();
                                    }
                                }
                            });
                    loginButton.setEnabled(true);// 设置登录按钮可以使用
                }
            }
        });
        getVersionName();

    }

    /**
     * 获取版本名称,,,检查自动更新
     */
    private void getVersionName() {
        int versionCode = BuildConfig.VERSION_CODE;
        String versionName = BuildConfig.VERSION_NAME;

        // 初始化OkHttpClient（主要是初始化连接超时时间）
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                .build();
        OkHttpUtils.initClient(okHttpClient);
        String url = IPConfig.baseUrl + "/flower/app/update?version=" + versionName;
        // 使用OkHttpUtils发起http请求并得到返回结果
        OkHttpUtils
                .get().url(url)
                .addHeader("Connection", "close")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONObject resultJson = JSON.parseObject(result);
                            String newVersion = resultJson.getString("version");
                            String donloadUrl = resultJson.getString("downloadUrl");
                            String contexts = resultJson.getString("contexts");
                            if (StringUtils.isNotBlank(newVersion)) {
                                AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
                                alertDialog.setTitle("更新提醒");
                                alertDialog.setMessage("当前版本：" + versionName + ";\n最新版本：" + newVersion + "；\n更新内容：" + contexts + ";\n\n是否更新？");
                                alertDialog.setButton(DialogInterface.BUTTON1, "确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (StringUtils.isNotBlank(donloadUrl)) {
                                            final Uri uri = Uri.parse(donloadUrl);
                                            final Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                            startActivity(it);
                                        }
                                    }
                                });
                                alertDialog.setButton(DialogInterface.BUTTON2, "取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        alertDialog.hide();
                                    }
                                });
                                alertDialog.show();
                            }
                        }
                    }
                });

    }

    private void getYanZhengMa() {
        int versionCode = BuildConfig.VERSION_CODE;
        String versionName = BuildConfig.VERSION_NAME;
        timeInMillis = Calendar.getInstance().getTimeInMillis();

        Log.e("Tag", String.valueOf(timeInMillis) );
        Log.e("Tag", String.valueOf(timeInMillis) );
        Log.e("Tag", String.valueOf(timeInMillis) );
        String url = IPConfig.baseUrl + "/sys/randomImage/" + timeInMillis;
        // 使用OkHttpUtils发起http请求并得到返回结果
        OkHttpUtils
                .get().url(url)
                .addHeader("Connection", "close")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);// 设置加载效果不可见
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String base64Str = JSON.parseObject(response).getString("result");
                            base64Str = base64Str.replace("data:image/jpeg;base64,", "");
                            base64Str = base64Str.replace("data:image/jpg;base64,", "");
                            byte[] decodedString = Base64.decode(base64Str, Base64.DEFAULT);
//系统api加载，byte转bitmap
                            Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                            yangzhengma.setImageBitmap(decodedByte);

                        } else {
                            yangzhengma.setImageURI(Uri.parse(""));
                        }

                    }
                });

    }

    @Override //点击返回实体键
    public void onBackPressed() {
        if (System.currentTimeMillis() - mExitTime < 2000) {
            super.onBackPressed();
            finish();
        } else {
            mExitTime = System.currentTimeMillis();
            Toast.makeText(LoginActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
        }
    }

    public void initViews() {
        yangzhengma = findViewById(R.id.yangzhengma);
        loginAccount = findViewById(R.id.loginAccount);
        loginPassword = findViewById(R.id.loginPassword);
        yanzhengmaValue = findViewById(R.id.yanzhengmaValue);
        loginButton = findViewById(R.id.login_button);
        progressBar = findViewById(R.id.login_progressBar);
        checkBox = findViewById(R.id.checkBox);
    }
}